define(function(require){
	$(function(){
		/*---------- 广告位管理——管理员 ----------*/
		
		/* 广告位数据-Table */
		var bodyTemplate = ['<tr position_id={id}>',
			                    '<td class="txtc"><a href="/trp/traffic/?position_id={id}" title="{name}">{name}</a></td>',
			                    '<td class="txtl">{attrs}</td>',
			                    '<td class="txtc">{width}</td>',
			                    '<td class="txtc">{height}</td>',
			                    //'<td class="txtc">{max}</td>',
			                    '<td class="txtc">{types}</td>',
			                    '<td class="txtr">{size}</td>',
			                    '<td class="txtc">{max}</td>',
			                    '<td class="txtc">{showType}</td>',
	 	                     	'<td class="txtc">',
	 	                     		'<a class="ibtn buytraffic" href="javascript:;" title="购入流量"><span class="glyphicon glyphicon-log-in"></span></a>',
	 	                     		'<a class="ibtn getcode" href="javascript:;" title="获取代码"><span class="glyphicon glyphicon-new-window"></span></a>',
	 	                     		'<a class="ibtn showchart" href="javascript:;" title="查看报表"><span class="glyphicon glyphicon-list-alt"></span></a>',
	 	                     		'<a class="ibtn editbtn" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
	 	                     		'<a class="ibtn delbtn" can_deleted="{can_deleted}" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove"></span></a>',
		                     		'</td>',
	 	                     '</tr>'].join('');
    	 
		var mediaId = $('#mediaId').val(),
			grid = Grid.init({
	            holder:'positionList',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/position/get_positions/',
	            pageTemplate:semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
		
		//数据重置：展示类型   0默认    1轮播图    2通栏    3自定义模板
    	grid.modifyModel(function(data){
        	if(data.showType==1){
        		data.showType = '轮播图';
        	}else if(data.showType==2){
        		data.showType = '通栏';
        	}else if(data.showType==3){
        		data.showType = '自定义模板';
        	}else{
        		data.showType = '默认';
        	}
        	if(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(data.size)){
        		data.size = data.size+'KB'
        	}else{
        		data.size = '无限制';
        	}
    	});
    	
		grid.onfilled(function(data){
			grid.data = data;
        	$('#positionList .delbtn').each(function(){
        		var $this = $(this);
        		var can_deleted = $this.attr('can_deleted');
        		//console.log(can_deleted)
        		if(can_deleted=='false'){
        			$this.addClass('disabled').removeClass('delbtn');
        		}
        	});
        	$('.ibtn').tooltip();
        });
		
	    //数据搜索 
		var filterData = function(pno){
	    	var txt = $('.searchbox-ipt').val(),
	    		size = $('.pageheader [name=measure]').val(),
	    		width = '', height = '',
		    	pageSize = 20;
	    	
	    	if(size!=-1){
	    		size = size.split('x');
	    		width = size[0];
	    		height = size[1];
	    	}
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
	        	
	        grid.send({
	        	mediaId: mediaId,
	        	searchTxt: txt,
	        	width: width,
	        	height: height,
	    		pageSize: pageSize,
	    		pageNo: pno || 1
	    	});
	    };
	    filterData()
	    
        //按尺寸搜索
	    $('.pageheader [name=measure]').select2({
        	ajax: {
        		url: '/trp/position/get_position_size/?media_id='+mediaId,
        		results: function(data){
        			var resultArr = [{id:'', text:'全部尺寸'}];
        			$.each(data.data, function(i,n){
        				var val = n.width+'x'+n.height;
        				resultArr.push({id:val, text:val});
        			});
        			return {results: resultArr}
        		}
        	}
        }).on('change', function(){
        	filterData();
        });
        /*$ajax.ajax({
        	url: '/trp/position/get_position_size',
        	data: {
        		media_id: mediaId
        	},
        	success: function(data){
        		sizeoption = '';
       			$.each(data.data, function(i,n){
       				sizeoption += '<option value="'+n.width+'x'+n.height+'">'+n.width+'x'+n.height+'</option>'
       			});
        		$('.pageheader [name=measure]').append(sizeoption).removeAttr('disabled').on('change', filterData).select2();
        	}
        });*/
	    
	    //按广告位名称、属性模糊搜索
	    $('.pageheader .searchbox-btn').on('click', function(){
	    	filterData();
	    });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
	    
	    var temp_attrsOp = '', temp_typesOp = '';
	    var getAttrs = function(callback){
   			 $ajax.ajax({
           		 url: '/trp/positionattr/get_position_attrs/',
           		 success: function(data){
       			 	temp_attrsOp = '';
           			 $.each(data.attrs, function(i,n){
           				 temp_attrsOp += '<option value="'+n.id+'">'+n.name+'</option>'
           			 });
           			 $ajax.ajax({
    	           		 url: '/trp/material/get_material_type/',
    	           		 success: function(data){
           			 		temp_typesOp = '';
    	           			$.each(data.data, function(i,n){
    	           				temp_typesOp += '<option value="'+n.id+'">'+n.name+'</option>'
    	           			});
    	           			if(!semi.utils.isEmpty(callback) && $.isFunction(callback))callback.call(this);
    	           		 },
    	           		 error: function(){
        					$dialog.alert('获取广告位信息失败，请稍后重试！','warning');
    	           		 }
    	           	 });
           		 }
           	 });
	   	 }
	    
	    var initAttrs = function($node){
	    	if($('select[name=attrs]',$node).html()==''){
	    		$('select[name=attrs]',$node).html(temp_attrsOp);
	    	}
   		 	$('select[name=attrs]',$node).select2({
				formatResult: function(state) {
				    return state.text + '<a class="pull-right red delattr" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove font12"></span></a>';
				},
			    allowClear: true
		    }).on('select2-selecting', function(e){
		    	var isdel = $(e.target).data('delattr');
		    	if(!semi.utils.isEmpty(isdel) && isdel){
		    		$(e.target).data('delattr',false);
		    		$('select[name=attrs]',$node).select2('close');
		    		semi.utils.stopDefault(e);
		    		$ajax.ajax({
		    			url: '/trp/positionattr/do_check/',
		    			data: JSON.stringify({
		    				position_attr_id: e.val
		    			}),
		    			contentType : "application/json",
	                    type : 'POST',
	                    dataType : 'json',
		    			success: function(data){
		    				//返回:{"related":true or false} 
		    				//seajs.log(data.tag);
		    				var $dlg = $dialog.confirm({
		                		title: '广告位属性删除',
		                        content: '广告位属性 【'+e.choice.text+'】 '+(data.related?'<b class="red">有</b>':'<b>无</b>')+'关联的广告位，您确定要删除该属性吗？',
		                        ok: function(){
		                        	var $dlg = this;
		                        	$ajax.ajax({
		                        		url: '/trp/positionattr/do_delete/',
		                        		data: JSON.stringify({
		                        			position_attr_id: $dlg.id
		        		    			}),
		        		    			contentType : "application/json",
		        	                    type : 'POST',
		        	                    dataType : 'json',
		                                success: function(){
		                                	$('select[name=attrs] [value='+$dlg.id+']',$node).remove();
		                                	$dlg.close().remove();
		                                	//$dialog.alert('删除广告位属性成功！','success');
		                                },
		        	                    error: function(){
		        	                    	$dlg.close().remove();
		        	                    	$dialog.alert('删除广告位属性失败，请稍后重试！','warning');
		        	                    }
		                        	});
		                        	return false;
		                        }
		                	});
		                	$.extend($dlg,{id:e.val});
		    			}
		    		});
		    	}
		    });
   	 	}
	    $(document).on('mouseenter','.delattr',function(){
	   		 $('.ui-dialog-content [name=attrs]').data('delattr',true);
	   	 });
	   	 $(document).on('mouseleave','.delattr',function(){
	   		 $('.ui-dialog-content [name=attrs]').data('delattr',false);
	   	 });
	   	 
	    require('validate');
	    /* 新增广告位+修改广告位-dialog */
	    $(document).on('click', '.createposition,.editbtn', function(){
        	var $this = $(this), isedit = false,
        		op = {
        			title: '新增广告位',
        			url: '/trp/position/do_create/'
        		};
        	
        	if($this.hasClass('editbtn')){
        		isedit = true;
        		$.extend(op, {
        			title: '修改广告位',
        			position_id: $this.parents('tr:first').attr('position_id'),
        			getdataurl: '/trp/position/get_position',
        			url: '/trp/position/do_modify/'
        		});
        	}
        	
			var customKey = 'material="true"',
				customTip = '<label generated="true" class="error" style="color:#666;">请在模板中使用 <b>material="true"</b> 标记素材位置，如：<br/><code>&lt;img '+customKey+' style="width:100%;border-radius:100%;"/&gt;</code></label>',
        		$dlg = $dialog({
        			id: 'popCreatePosition',
        			title: op.title,
        			width: '620px',
        			onshow: function(){
        				var $d = this, $node = $($d.node), isedit = this.isedit;
        				getAttrs(function(){
        				var initDlg = function(callback){
        					$d.content($('.pop-createposition').clone().show()[0]);
            				$('select[name=attrs]',$node).html(temp_attrsOp);
            				$('select[name=types]',$node).html(temp_typesOp);
            				$('[name=customtmpl]',$node).after(customTip);
            				
            				$('[name=customtmpl]',$node).on('focus', function(){
            					$('[name=customtmpl]',$node).siblings('label.error').remove();
            					$('[name=customtmpl]',$node).after(customTip);
            				});
            				$('.traffic-open',$node).on('click', function(){
                 				$(this).removeClass('btn-default').addClass('btn-success').siblings('.btn').removeClass('btn-danger').addClass('btn-default');
                 				$('[name=can_deleted]',$node).val(true);
                 			});
         					$('.traffic-close',$node).on('click', function(){
         						$(this).removeClass('btn-default').addClass('btn-danger').siblings('.btn').removeClass('btn-success').addClass('btn-default');
         						$('[name=can_deleposition_idted]',$node).val(false);
                 			});
         					$('[name=max]',$node).on({
         						keyup: function(){
	         						var $this = $(this), thisval = $this.val();
	         						if(thisval.length>0 && !/^\d+$/.test(thisval)){
	         							$this.val(thisval.replace(/\D/g,''));
	         						}
	         						thisval = parseInt($this.val());
	         						if(thisval==1){
	         							$('[showtype=0],[showtype=3]',$node).removeClass('disabled');
	         							$('[showtype=1],[showtype=2]',$node).addClass('disabled');
	         							if(!$('[showtype=0]',$node).hasClass('btn-success') && !$('[showtype=3]',$node).hasClass('btn-success')){
	         								$('[showtype=0]',$node).click();
	         							}
	         						}else if(thisval>1){
	         							$('[showtype=1],[showtype=2],[showtype=3]',$node).removeClass('disabled');
	         							$('[showtype=0]',$node).addClass('disabled');
	         							if($('[showtype=0]',$node).hasClass('btn-success')){
	         								$('[showtype=1]',$node).click();
	         							}
	         						}
	         					},
	         					change: function(){
	         						var $this = $(this), thisval = parseInt($this.val());
	         						if(thisval==1){
	         							$('[showtype=0],[showtype=3]',$node).removeClass('disabled');
	         							$('[showtype=1],[showtype=2]',$node).addClass('disabled');
	         							if(!$('[showtype=0]',$node).hasClass('btn-success') && !$('[showtype=3]',$node).hasClass('btn-success')){
	         								$('[showtype=0]',$node).click();
	         							}
	         						}else if(thisval>1){
	         							$('[showtype=1],[showtype=2],[showtype=3]',$node).removeClass('disabled');
	         							$('[showtype=0]',$node).addClass('disabled');
	         							if($('[showtype=0]',$node).hasClass('btn-success')){
	         								$('[showtype=1]',$node).click();
	         							}
	         						}
	         					}
         					});
         					$('.showtype .btn',$node).on('click', function(){
         						var $this = $(this), showtype = $this.attr('showtype');
         						
         						$this.addClass('btn-success').siblings('.btn-success').removeClass('btn-success');
     							if(showtype == '0'){
     								$('.slidetime,.arraytype,.customtmpl',$node).slideUp('fast');
         						}else if(showtype == '1'){
         							$('.arraytype,.customtmpl',$node).slideUp('fast');
         							$('.slidetime',$node).slideDown('fast');
         						}else if(showtype == '2'){
         							$('.slidetime,.customtmpl',$node).slideUp('fast');
         							$('.arraytype',$node).slideDown('fast');
         						}else if(showtype == '3'){
         							$('.slidetime,.arraytype',$node).slideUp('fast');
         							$('.customtmpl',$node).slideDown('fast');
         						}
         					});
         					$('.arraytype .btn',$node).on('click', function(){
         						$(this).addClass('btn-success').siblings('.btn-success').removeClass('btn-success');
         					});
         					
         					if(!semi.utils.isEmpty(callback) && $.isFunction(callback))callback.call(this);
        				}
     					
 						if(!isedit){
 							initDlg(function(){
 								$('select[name=types] option',$node).attr('selected','selected');
 								$('select[name=types]',$node).select2({allowClear: true}).on('select2-open', function(){
 									$(this).removeClass('error').siblings('label.error').remove();
 								});
 								initAttrs($node);
 							});
							return;
 						}
     					
     					$ajax.ajax({
                			url: op.getdataurl,
                			data: {
                				id: op.position_id
                			},
                			success: function(data){
                				//{"name": "media 1 position 1", "min": 3, "max": 3, "height": 100, "width": 200, "attrs": "", "can_deleted": 1, "id": 1, "types": "", "size": 7168}
                				initDlg(function(){
            						$('[name=name]',$node).val(data.name);
                    				$.each(data.attrs, function(i,n){
                    					$('select[name=attrs] option[value='+n.id+']',$node).attr('selected','selected');
                    				});
                    				$('[name=width]',$node).val(data.width);
                    				$('[name=height]',$node).val(data.height);
                    				$.each(data.types, function(i,n){
                    					$('select[name=types] option[value='+n.id+']',$node).attr('selected','selected');
                    				});
                    				$('select[name=types]',$node).select2({allowClear: true}).on('select2-open', function(){
     									$(this).removeClass('error').siblings('label.error').remove();
     								});;
                    				if(/^\d+$/.test(data.size))$('[name=size]',$node).val(data.size);
                    				$('[showtype='+data.showType+']',$node).addClass('btn-success').siblings('.btn-success').removeClass('btn-success');
                    				$('[name=time]',$node).val(data.time);
                    				$('[arraytype='+data.arrayType+']',$node).addClass('btn-success').siblings('.btn-success').removeClass('btn-success');
                    				$('[name=customtmpl]',$node).val(data.code);
                    				$('[name=max]',$node).val(data.max).change();
                    				$('.showtype .btn-success',$node).click();
                    				initAttrs($node);
            					});
                			},
                			error: function(){
                				$dlg.close().remove();
                				$dialog.alert('获取广告位信息失败，请稍后重试！','warning');
                			}
                		});
        			});
            	},
            	button:[{
            		value: '取消'
            	},{
            		value: '预览',
            		callback: function(){
            			var $node = $(this.node),
            				width = $('[name=width]',$node).val(),
            				height = $('[name=height]',$node).val(),
            				num = $('[name=max]',$node).val(), 
        					showtype = $('.btn-success[showtype]',$node).attr('showtype'), 
        					time = $('[name=time]',$node).val(),
        					arraytype = $('.btn-success[arraytype]',$node).attr('arraytype'),
        					customtmpl = $('[name=customtmpl]',$node).val();
            			
            			if(!$('[name=width],[name=height],[name=types]',$node).valid())return false;
            			if(showtype == 3){
            				var _sum = 0, _tmpl = customtmpl;
            				while(_tmpl.indexOf(customKey) != -1){
            					_tmpl = _tmpl.replace(customKey,'');
            					_sum++;
            				}
            				if(_sum != num){
            					$('[name=customtmpl]',$node).siblings('label.error').remove();
            					$('[name=customtmpl]',$node).after('<label for="customtmpl" generated="true" class="error" style="bottom:10px;">模板中素材位置 <b style="color:#666;">'+customKey+'</b> 数量与分栏数不相等，请检查！</label>');
            					return false;
            				}
            			}
            			require.async('./common/popposition', function($position){
            				$position.show({
            					width: width,
            					height: height,
            					num: num,
            					showtype: showtype,
            					time: time,
            					arraytype: arraytype,
            					customtmpl: customtmpl,
            					key: customKey
            				});
            			});
        				
            			return false;
            		}
            	},{
            		value: '确定',
            		callback: function(){
	            		var $node = $(this.node),
	            			isedit = this.isedit,
		        			data = {
		            			mediaId: mediaId,
		                    	name: $('[name=name]',$node).val(),
		                    	attrs: $('[name=attrs]',$node).val(),
		                    	width: $('[name=width]',$node).val(),
		                    	height: $('[name=height]',$node).val(),
		                    	size: $('[name=size]',$node).val(),
		                    	types: $('[name=types]',$node).val(),
		                    	max: $('[name=max]',$node).val(),
		                        min: $('[name=max]',$node).val(),
		                        showType: $('.btn-success[showtype]',$node).attr('showtype'),
		                        time: $('[name=time]',$node).val(),
		                        arrayType: $('.btn-success[arraytype]',$node).attr('arraytype'),
		                        code: $('[name=customtmpl]',$node).val()
		        			};
	            		
		            	if(!$('form',$node).valid())return false;
		        		if(isedit)$.extend(data, {position_id: op.position_id});
		        		if(data.showType!='3')data.code = '';
		        		$ajax.ajax({
		        			url: op.url,
		            		data: JSON.stringify(data),
		            		contentType : "application/json",
		                    type : 'POST',
		                    dataType : 'json',
		                    success: function(){
		                    	$dlg.close().remove();
		                    	$dialog.alert(op.title+'成功！','success');
		                    	if(isedit){
		                    		filterData(semi.utils.gridPage(grid));
		                    	}else{
		                    		filterData();
		                    	}
		                    },
		                    error: function(){
		                    	$dlg.close().remove();
		                    	$dialog.alert(op.title+'失败，请稍后重试！','warning');
		                    }
		            	 });
		            	return false;
		            },
                    autofocus: true
            	}]
            });
			$.extend($dlg,{isedit:isedit});
			$dlg.showModal();
        });
	    
	    /* 删除广告位-dialog */
        $(document).on('click', '.delbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), position_id = $tr.attr('position_id');
        	var $dlg = $dialog.confirm({
        		title: '删除广告位',
                content: '您确定要删除该广告位吗？',
                ok: function(){
                	var $dlg = this;
                	$ajax.ajax({
                    	url: '/trp/position/do_delete/',
                        data: {
                        	position_id: $dlg.position_id
        				},
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('删除广告位成功！','success');
                        	filterData(semi.utils.gridPage(grid));
                        },
	                    error: function(){
	                    	$dlg.close().remove();
	                    	$dialog.alert('删除广告位失败，请稍后重试！','warning');
	                    }
                    });
                	return false;
                }
        	});
        	$.extend($dlg,{position_id:position_id});
        });
        
        /* 购入流量 */
        $(document).on('click', '.buytraffic', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), position_id = $tr.attr('position_id');
        	var $dlg = $dialog({
        		title: '购入流量',
        	    width: '520px',
        	    onshow: function() {
        	    	var $d = this, $node = $($d.node),
        	    		initDlg = function(time){
	        	    		//购买方式CPM:1  CPD:0
	            			//是否共享 1是 0否
	            	    	$d.content($('.pop-buytraffic').clone().show()[0]);
	            	    	$('[name=bid_type]',$node).on('change', function(){
	                	 		//购买方式CPM:1  CPD:0
	                	 		$(this).val()=='1'?$('.unit',$node).html('元 / CPM'):$('.unit',$node).html('元 / 天');
	             			}).select2();
	                	 	$('[name=bid_type]',$node).change();
	                	 	$('[name=circle]',$node).daterangepicker({
        			            format:'YYYY-MM-DD',
        			            minDate: time
        			        });
	                	 	$('[name=shared]',$node).val(0);
	                    	$('.shared',$node).on('click', function(){
	             				$(this).addClass('btn-success').removeClass('btn-default').siblings('.btn').removeClass('btn-danger').addClass('btn-default');
	             				$('.shared_other',$node).hide();
	             				$('[name=shared]',$node).val(0);
	             				$('[name=floor]',$node).removeClass('required');
	             			});
	     					$('.noshared',$node).on('click', function(){
	     						$(this).addClass('btn-danger').removeClass('btn-default').siblings('.btn').removeClass('btn-success').addClass('btn-default');
	     						$('.shared_other',$node).show();
	     						$('[name=shared]',$node).val(1);
	     						$('[name=floor]',$node).addClass('required');
	             			});
	     					$node.initUI();
	        	    	};
	        	    semi.utils.getSTime(initDlg);
        	    },
        	    okValue: '确定',
        	    ok: function(){
	               	 var $d = this, $node = $($d.node);
	            	 var circle = $('[name=circle]',$node).val().split(' 至 ');
	            	 if(!$('form',$node).valid())return false;
	 	 			$ajax.ajax({
	             		url: '/trp/traffic/do_create',
	             		data: JSON.stringify({
	             			position_id: position_id,
	                 		start: circle[0],
	                 		end: circle[1],
	                 		bid_type: $('[name=bid_type]',$node).val(),
	                 		bid_price: $('[name=bid_price]',$node).val(),
	                 		estimated_imp: $('[name=pv]',$node).val(),
	                 		estimated_click: $('[name=click]',$node).val(),
	                 		shared: $('[name=shared]',$node).val(),
	                 		floor: $('[name=floor]',$node).val()
	             		}),
	             		contentType : "application/json",
	                     type : 'POST',
	                     dataType : 'json',
	             		success: function(data){
	             			$d.close().remove();
	             			$dialog.alert('购入流量成功！','success');
	             			filterData(semi.utils.gridPage(grid));
	             		},
	             		error: function(data){
	             			if (data.message=="date.illegal"){
	             				$dialog.alert('购入流量失败，多个流量购入日期有重叠！','warning');
	             			}else{
	             				$dialog.alert('购入流量失败，请稍后重试！','warning');
	             			}
	             		}
	             	 });
	             	 return false;
        	    },
        	    cancelValue: '取消',
        	    cancel: true
        	}).showModal();
        });
        
        /* 查看报表-dialog */
        var $popchart = require('./common/popchart');
        $(document).on('click', '.showchart', function(){
        	var $this = $(this), position_id = $this.parents('tr:first').attr('position_id');
        	$popchart({
            	title: '广告位报表',
            	btn: $this,
            	dataurl: '/trp/position/get_position_report/',
            	type: 'position',
            	idname: 'position_id',
            	idvalue: position_id
            });
        });

        /* 获取嵌码-dialog */
        $(document).on('click', '.getcode', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), position_id = $tr.attr('position_id');
        	$dialog({
                title: '获取嵌码',
                width: '600px',
                onshow: function(){
                	var $d = this, $node = $(this.node);
                	$ajax.ajax({
                    	url: '/trp/position/get_position_code',
                    	data: {
                    		position_id: position_id
                    	},
                        type : 'GET',
                        dataType : 'json',
                        success: function(data){
                        	data.code = encodeURIComponent(data.code);
                        	$d.content($('.pop-tf').clone().show()[0]);
                        	var $frameCode = $('.frameCode textarea',$node),
	                    		$jsCode = $('.jsCode textarea',$node),
	                    		jsTmpl = $jsCode.val(),
	                    		tmpl_start = '<iframe width="{width}" height="{height}" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" allowtransparency="true" src="{prefix}?_srv=GOME&l={position_id}&w={width}&h={height}&max={max}&showtype={showtype}&time={time}&arraytype={arraytype}&code={code}',
	                    		tmpl_end = '"></iframe>',
	                    			
	                    	tmpl_start = tmpl_start.replaceAll('{width}',data.width)
	                    						   .replaceAll('{height}',data.height)
	                    						   .replace('{prefix}',data.prefix)
	                    						   .replace('{position_id}',position_id)
	                    						   .replace('{max}',data.max)
	                    						   .replace('{showtype}',data.showType)
	                    						   .replace('{time}',data.time)
	                    						   .replace('{arraytype}',data.arrayType)
	                    						   .replace('{code}',data.code);
	                    	$frameCode.val(tmpl_start+tmpl_end);
	                    	
	                    	// JavaScript
	                    	var jscode = $jsCode.val();
	                    	jscode = jscode.replace('{serving}',data.serving)
	    	 						 .replaceAll('{pid}',position_id)
	    	 						 .replace('{width}',data.width)
	    	 						 .replace('{height}',data.height)
	    	 						 .replace('{max}',data.max)
	    	 						 .replace('{showtype}',data.showType)
	    	 						 .replace('{time}',data.time)
	    	 						 .replace('{arraytype}',data.arrayType)
	    	 						 .replace('{code}',data.code)
	    	 						 .replace('{src}','')
	    	 						 .replace('{ldp}','')
	    	 						 .replace('{timeout}','1000')
	    	 						 .replace('{k1}','')
	    	 						 .replace('{k2}','')
	    	 						 .replace('{k3}','');
	    	 				$jsCode.val(jscode);
	    	 				require.async('codemirror', function($code){
	    	 					$code.load('javascript', function(){
	    	 						var frameEditor = CodeMirror.fromTextArea($frameCode[0], {lineNumbers: true});
	                        		$code.theme(frameEditor, 'monokai');
	                        		
	                        		var jsEditor = CodeMirror.fromTextArea($jsCode[0],{lineNumbers: true});
	                        		$code.theme(jsEditor, 'monokai');
	                        		$('[name=ldp]',$node).on('change', function(){
	    	                    		var _url = $(this).val();
	    	                    		if(!semi.utils.isEmpty(_url) && !semi.utils.isGomeUrl(_url)){
	    		            				$(this).addClass('error').css('margin-bottom','10px').siblings('label.error').remove();
	    		            				$(this).after('<label class="error" style="position:absolute;top:auto;bottom:0;">请填写国美站内链接</label>');
	    		            			}else{
	    		            				$(this).removeClass('error').siblings('label.error').remove();
	    		            			}
	    	                    	});
	                        		$('[name=src],[name=ldp],[name=timeout],[name=k1],[name=k2],[name=k3]',$node).on('keyup', function(){
	                            		var src = $('[name=src]',$node).val(), 
	                            			ldp = $('[name=ldp]',$node).val().toUrl(), 
	                            			timeout = $('[name=timeout]',$node).val(),
	                            			k1 = $('[name=k1]',$node).val(),
	                            			k2 = $('[name=k2]',$node).val(),
	                            			k3 = $('[name=k3]',$node).val();
	                            		
	                            		if($(this).attr('name')=='ldp')$(this).removeClass('error').siblings('label.error').remove();
	                            		if($(this).attr('name')=='k2'){
	                            			if(semi.utils.isEmpty($('[name=k1]',$node).data('value'))){
	                            				$('[name=k1]',$node).val(k2);
	                            			}
	                            		}else if($(this).attr('name')=='k3'){
	                            			if(semi.utils.isEmpty($('[name=k1]',$node).data('value'))){
	                            				$('[name=k1]',$node).val(k3);
	                            			}
	                            			if(semi.utils.isEmpty($('[name=k2]',$node).data('value'))){
	                            				$('[name=k2]',$node).val(k3);
	                            			}
	                            		}
	                            		
	                            		$frameCode.val(tmpl_start + 
	                            						(semi.utils.isEmpty(src)?'':'&src='+src.toUrl()) + 
	                            						(semi.utils.isEmpty(ldp)?'':'&ldp='+ldp.toUrl()) + 
	                            						(semi.utils.isEmpty(timeout)?'':'&timeout='+timeout) +
	                            						(semi.utils.isEmpty(k1)?'':'&k1='+k1) +
	                            						(semi.utils.isEmpty(k2)?'':'&k2='+k2) +
	                            						(semi.utils.isEmpty(k3)?'':'&k3='+k3) +
	                            						tmpl_end);
	                            		frameEditor.doc.setValue($frameCode.val());
	                            		
	                            		var _jscode = jsTmpl;
	                            		_jscode = _jscode.replace('{serving}',data.serving)
	    						 						 .replaceAll('{pid}',position_id)
	    						 						 .replace('{width}',data.width)
	    						 						 .replace('{height}',data.height)
	    						 						 .replace('{max}',data.max)
	    						 						 .replace('{showtype}',data.showType)
	    						 						 .replace('{time}',data.time)
	    						 						 .replace('{arraytype}',data.arrayType)
	    						 						 .replace('{code}',data.code)
	    						 						 .replace('{src}',src)
	    						 						 .replace('{ldp}',ldp)
	    						 						 .replace('{timeout}',timeout)
	    						 						 .replace('{k1}',k1)
	    						 						 .replace('{k2}',k2)
	    						 						 .replace('{k3}',k3);
	                            		$jsCode.val(_jscode);
	                            		jsEditor.doc.setValue($jsCode.val());
	                        		});
	                        		$('[name=src],[name=ldp],[name=timeout],[name=k1],[name=k2],[name=k3]',$node).on('blur', function(){
	                        			$('[name=src],[name=ldp],[name=timeout],[name=k1],[name=k2],[name=k3]',$node).each(function(){
	                            			$(this).data('value', $(this).val());
	                            		});
	                        		});
	                        		$('[name=src],[name=ldp],[name=timeout],[name=k1],[name=k2],[name=k3]',$node).each(function(){
	                        			$(this).data('value',$(this).val());
	                        		});
	    	 					});
	                    	});
	                    	
	                    	require.async('copy', function($copy){
	                    		$copy.init({
	                      	          item: $('.ui-dialog-button button:eq(1)',$node),
	                  	          	  content: $frameCode,
	                      	          title: '复制Iframe投放代码',
	                      	          mouseover: function(client){
	                      	     	     //client.setText($jsCode.val());
	                      	          },
	                      	          mousedown: function(){
	                      	        	seajs.log(1)
	                      	        	return false;
	                      	          },
	                      	         callback: function(data){
	                      	     	     $dialog.alert('复制Iframe投放代码成功！','success');
	                      	         }
	                      	     });
	                    		$copy.init({
	                    	          item: $('.ui-dialog-button button:eq(2)',$node),
	                    	          content: $jsCode,
	                    	          title: '复制JavaScript投放代码',
	                    	          mouseover: function(client){
	                    	     	     //client.setText($frameCode.val());
	                    	          },
	                    	         callback: function(data){
	                    	     	     $dialog.alert('复制JavaScript投放代码成功！','success');
	                    	         }
	                    	     });
	                    	});
                        },
                        error: function(){
                        	$dialog.alert('获取代码失败，请稍后重试！', 'warning', function(){
                        		$d.close().remove();
                        	});
                        }
                    });
                },
                button: [{
                	value: '关闭'
                },{
                	value: '复制Iframe投放代码',
                	callback: function(){
                		return false;
                	}
                },{
                	value: '复制JavaScript投放代码',
                	callback: function(){
                		return false;
                	},
                	autofocus: true
                }]
            }).showModal();
        });
        
        /* 新增广告位属性 */
        $(document).on('click', '.creatattr', function(){
        	var $curnode = $($dialog.get('popCreatePosition').node),
        		$dlg = $dialog({
	                title: '新增广告位属性',
	                content: $('.pop-createattr').clone().show()[0],
	                width: '500px',
    				zIndex: semi.utils.topIndex(),
	            	okValue: '确定',
	            	ok: function(){
	            		var $node = $(this.node), name = $('[name=attr_name]',$node).val();
	            		if(!$('form',$node).valid())return false;
	            		var repeat = false;
	            		$('[name=attrs] option',$curnode).each(function(){
	            			if($(this).text()==name)repeat = true;
	            		});
	            		if(repeat){
	            			$('[name=attr_name]',$node).addClass('error').siblings('label.error').remove();
	            			$('[name=attr_name]',$node).after('<label for="attr_name" generated="true" class="error">此属性已存在</label>');
	            			return false;
	            		}
	            		$ajax.ajax({
	            			url : '/trp/positionattr/do_create/',
	                		contentType : "application/json",
	                        type : 'POST',
	                        dataType : 'json',
	                		data: JSON.stringify({
	                			name: name,
	        				}),
	                        success: function(data){
	                        	$dlg.close().remove();
	                        	if($('[name=attrs]',$curnode).children().size()>0){
	                        		$('[name=attrs]',$curnode).children(':first').before('<option value="'+data.id+'">'+name+'</option>');
	                        	}else{
	                        		$('[name=attrs]',$curnode).append('<option value="'+data.id+'">'+name+'</option>');
	                        	}
	                        	//$dialog.alert('新增广告位属性成功！','success');
	                        },
	                        error: function(){
	                        	$dlg.close().remove();
	                        	$dialog.alert('新增广告位属性失败，请稍后重试！','warning');
	                        }
	                	 });
	                	return false;
	                },
	                cancelValue: '取消',
	                cancel: true
	            }).showModal();
        });

    });
});
